<template>
  <div class="devices-container">
    <PageHeader title="设备管理">
      <template #actions>
        <el-button type="primary" @click="handleAdd">新建设备</el-button>
      </template>
    </PageHeader>

    <main class="devices-content">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>设备列表</span>
            <el-input
              v-model="searchQuery"
              placeholder="搜索设备"
              style="width: 200px"
              clearable
            />
          </div>
        </template>

        <el-table :data="filteredDevices" style="width: 100%">
          <el-table-column prop="device_id" label="设备ID" min-width="120" align="center" />
          <el-table-column prop="name" label="设备名称" min-width="150" align="center" />
          <el-table-column prop="type" label="设备类型" min-width="120" align="center" />
          <el-table-column prop="location" label="位置" min-width="120" align="center" />
          <el-table-column label="最后更新时间" min-width="160" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.last_update) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="180" fixed="right" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" @click="viewDeviceDetails(scope.row)">查看详情</el-button>
              <el-button size="small" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- Device Details Dialog -->
      <el-dialog
        v-model="deviceDetailsVisible"
        title="设备详情"
        width="70%"
      >
        <div v-if="selectedDevice">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="设备ID">{{ selectedDevice.device_id }}</el-descriptions-item>
            <el-descriptions-item label="设备名称">{{ selectedDevice.name }}</el-descriptions-item>
            <el-descriptions-item label="设备类型">{{ selectedDevice.type }}</el-descriptions-item>
            <el-descriptions-item label="位置">{{ selectedDevice.location }}</el-descriptions-item>
            <el-descriptions-item label="最后更新时间">
              {{ formatDateTime(selectedDevice.last_update) }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="device-data-section">
            <h3>最近数据</h3>
            <el-table :data="deviceData" style="width: 100%">
              <el-table-column prop="timestamp" label="时间" align="center">
                <template #default="scope">
                  {{ formatDateTime(scope.row.timestamp) }}
                </template>
              </el-table-column>
              <el-table-column prop="operator" label="操作员" align="center" />
              <el-table-column prop="shift" label="班次" align="center" />
              <el-table-column prop="average_speed" label="平均车速" align="center">
                <template #default="scope">
                  {{ formatNumber(scope.row.average_speed) }} 米/分钟
                </template>
              </el-table-column>
              <el-table-column prop="shift_length" label="班次计米" align="center">
                <template #default="scope">
                  {{ formatNumber(scope.row.shift_length) }} 米
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>

      <!-- Add/Edit Device Dialog -->
      <el-dialog
        v-model="deviceDialogVisible"
        :title="dialogType === 'add' ? '新建设备' : '编辑设备'"
        width="50%"
      >
        <el-form :model="deviceForm" label-width="100px" :rules="rules" ref="deviceFormRef">
          <el-form-item label="设备ID" v-if="dialogType === 'add'">
            <el-input v-model="deviceForm.device_id" disabled />
          </el-form-item>
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="deviceForm.name" />
          </el-form-item>
          <el-form-item label="设备类型" prop="type">
            <el-select v-model="deviceForm.type" style="width: 100%">
              <el-option label="换位设备" value="换位设备" />
              <el-option label="组合设备" value="组合设备" />
              <el-option label="其他设备" value="其他设备" />
            </el-select>
          </el-form-item>
          <el-form-item label="位置" prop="location">
            <el-input v-model="deviceForm.location" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deviceDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useDashboardStore } from '@/stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../services/api'
import PageHeader from '../components/PageHeader.vue'

const store = useDashboardStore()
const searchQuery = ref('')
const deviceDetailsVisible = ref(false)
const deviceDialogVisible = ref(false)
const dialogType = ref('add')
const selectedDevice = ref(null)
const deviceData = ref([])
const deviceFormRef = ref(null)

const deviceForm = ref({
  device_id: '',
  name: '',
  type: '',
  location: ''
})

const rules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入设备位置', trigger: 'blur' }]
}

const devices = computed(() => store.devices)

// 合并搜索和状态过滤条件
const filteredDevices = computed(() => {
  // 首先过滤掉已删除的设备
  const nonDeletedDevices = devices.value.filter(device => device.status !== 'deleted')

  // 然后应用搜索过滤
  if (!searchQuery.value) return nonDeletedDevices

  const query = searchQuery.value.toLowerCase()
  return nonDeletedDevices.filter(device =>
    device.device_id.toLowerCase().includes(query) ||
    device.name.toLowerCase().includes(query) ||
    device.type.toLowerCase().includes(query) ||
    device.location.toLowerCase().includes(query)
  )
})

const generateDeviceId = () => {
  return `DEV-${Date.now()}`
}

const handleAdd = () => {
  dialogType.value = 'add'
  deviceForm.value = {
    device_id: generateDeviceId(),
    name: '',
    type: '换位设备',
    location: ''
  }
  deviceDialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  deviceForm.value = { ...row }
  deviceDialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除设备 "${row.name}"？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 使用 sendDeviceData 将设备状态更新为 deleted
      await api.sendDeviceData({
        device_id: row.device_id,
        status: 'deleted'
      })
      await store.fetchDeviceStatus() // 重新获取设备列表
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除设备失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户点击取消，不做任何操作
  })
}

const handleSubmit = async () => {
  if (!deviceFormRef.value) return

  await deviceFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('提交表单数据:', deviceForm.value)
        if (dialogType.value === 'add') {
          console.log('调用 createDevice API')
          const response = await api.createDevice(deviceForm.value)
          console.log('createDevice API 响应:', response)
        } else {
          console.log('调用 updateDevice API')
          const response = await api.updateDevice(deviceForm.value.device_id, deviceForm.value)
          console.log('updateDevice API 响应:', response)
        }
        await store.fetchDeviceStatus()
        deviceDialogVisible.value = false
        ElMessage.success(dialogType.value === 'add' ? '创建成功' : '更新成功')
      } catch (error) {
        console.error('API 调用失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '创建失败' : '更新失败')
      }
    }
  })
}

const getStatusType = (status) => {
  switch (status) {
    case 'online': return 'success'
    case 'offline': return 'info'
    case 'error': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'online': return '在线'
    case 'offline': return '离线'
    case 'error': return '故障'
    default: return '未知'
  }
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

const formatNumber = (num) => {
  if (num === undefined || num === null) return ''
  return num.toFixed(2)
}

const viewDeviceDetails = async (device) => {
  selectedDevice.value = device
  deviceDetailsVisible.value = true

  try {
    const response = await api.getDeviceData(device.device_id, 10)
    deviceData.value = response.data.data
  } catch (error) {
    console.error('Error fetching device data:', error)
    ElMessage.error('获取设备数据失败')
    deviceData.value = []
  }
}

onMounted(async () => {
  if (devices.value.length === 0) {
    await store.fetchDeviceStatus()
  }
})
</script>

<style scoped>
.devices-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.devices-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.device-data-section {
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}

:deep(.el-button--small) {
  padding: 5px 12px;
  font-size: 12px;
}
</style>






